/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.toools.gwt.wmc.server.dao.toplink;

import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import org.toools.gwt.wmc.client.exceptions.dao.EmailExistsException;
import org.toools.gwt.wmc.client.exceptions.dao.WrongLoginException;
import org.toools.gwt.wmc.server.dao.IAccountDAO;
import org.toools.gwt.wmc.jpa.Account;

/**
 *
 * @author ich
 */
public class AccountDAO implements IAccountDAO{

    public Account getAccountByID(Integer id) {
        Account result;
        try {
            result = (Account) EMFKeeper.EM.createNamedQuery("Account.getById").setParameter("id", id).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        System.out.println("fetched account " + result.getId() + " from db.");
        return result;
    }

    public Collection<Account> getAccounts() {

        Collection<Account> ret = EMFKeeper.EM.createNamedQuery("Account.getAll").getResultList();

        System.out.println("fetched " + ret.size() + " accounts from db.");
        return ret;
    }

    public Account Login(String email, String pwd) throws WrongLoginException {

        Account result;
        try {
            result = (Account) EMFKeeper.EM.createNamedQuery("Account.getByEmail").setParameter("email", email).getSingleResult();
        } catch (NoResultException e) {
           throw new WrongLoginException();
        }
        
        if( !result.getPassword().equals( pwd ) )
            throw new WrongLoginException();

        System.out.println("fetched account " + result.getId() + " from db.");
        return result;
    }

    public Integer Register( Account a ) throws EmailExistsException {
        EMFKeeper.EM.getTransaction().begin();
        EMFKeeper.EM.persist( a );
        EMFKeeper.EM.flush();
        EMFKeeper.EM.getTransaction().commit();
        return a.getId();
    }

    public Boolean delete(Account a) {
        Account rem = (Account) EMFKeeper.EM.createNamedQuery( "Account.getById" ).setParameter( "id", a.getId() ).getSingleResult();
        return SimpleCUD.delete( rem );
    }

    public Boolean update(Account a) {
        return SimpleCUD.update( a );
    }
}
